from typing import Optional, List

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from database import get_db
from models.prescription_model import Prescription
from schemas.prescription_schemas import PrescriptionCreate, PrescriptionUpdate, PrescriptionResponse, \
    PrescriptionWithPaymentStatusResponse
from services.prescription_service import (
    get_prescription,
    get_prescriptions,
    create_prescription,
    update_prescription,
    delete_prescription,
    get_prescriptions_by_patient, get_paid_prescriptions, get_prescriptions_with_payment_status,
    get_unpaid_prescriptions_by_patient, pharmacist_deal_prescription
)
from services.auth_service import require_user
from models.user_models import UserType

router = APIRouter(prefix="/prescriptions")

@router.get("/", response_model=list[PrescriptionResponse])
def read_prescriptions(skip: int = 0, limit: int = 100, db: Session = Depends(get_db),
                      user=Depends(require_user(UserType.ADMIN))):
    prescriptions = get_prescriptions(db, skip=skip, limit=limit)
    return prescriptions

@router.post("/", response_model=PrescriptionResponse)      ##创建处方这一步其实就是医生写处方的过程
def create_new_prescription(prescription: PrescriptionCreate, db: Session = Depends(get_db),
                          user=Depends(require_user(UserType.ADMIN, UserType.DOCTOR))):
    return create_prescription(db, prescription,user['user_type']=="DOCTOR")

@router.get("/paid", response_model=list[PrescriptionWithPaymentStatusResponse])
def read_paid_prescriptions(
    db: Session = Depends(get_db),
    user=Depends(require_user(UserType.ADMIN, UserType.DOCTOR,UserType.PHARMACIST)),
):
    return get_paid_prescriptions(db)

@router.get("/{prescription_id}", response_model=PrescriptionResponse)
def read_prescription(prescription_id: int, db: Session = Depends(get_db),
                     user=Depends(require_user(UserType.ADMIN, UserType.DOCTOR, UserType.PATIENT))):
    return get_prescription(db, prescription_id)

@router.put("/{prescription_id}", response_model=PrescriptionResponse)
def update_existing_prescription(prescription_id: int, prescription: PrescriptionUpdate,
                               db: Session = Depends(get_db),
                               user=Depends(require_user(UserType.ADMIN, UserType.DOCTOR))):
    return update_prescription(db, prescription_id, prescription)

@router.delete("/{prescription_id}")
def delete_existing_prescription(prescription_id: int, db: Session = Depends(get_db),
                               user=Depends(require_user(UserType.ADMIN, UserType.DOCTOR))):
    return delete_prescription(db, prescription_id)

@router.get("/patient/{patient_id}", response_model=list[PrescriptionResponse])     ##病人可以从这里查看自己的处方表，也可以在总表上查询处方表ID
def read_patient_prescriptions(
    patient_id: int, 
    db: Session = Depends(get_db),
    payload: dict = Depends(require_user(UserType.ADMIN, UserType.DOCTOR, UserType.PATIENT))
):
    # 从payload中获取用户类型和ID
    user_type = UserType.from_str(payload.get("user_type"))
    user_ref_id = int(payload.get("user_ref_id"))
    
    # 如果是患者，只能查看自己的记录
    if user_type == UserType.PATIENT and user_ref_id != patient_id:
        raise HTTPException(
            status_code=403, 
            detail="Patients can only view their own records"
        )
    
    return get_prescriptions_by_patient(db, patient_id=patient_id)



@router.get("/with_payment_status/{patient_id}", response_model=list[PrescriptionWithPaymentStatusResponse])
def read_prescriptions_with_payment_status(
    patient_id: Optional[int],
    db: Session = Depends(get_db),
    user=Depends(require_user(UserType.ADMIN, UserType.DOCTOR, UserType.PATIENT))
):
    # 如果是患者，只能查看自己的处方
    user_type = user.get("user_type")
    user_ref_id = user.get("user_ref_id")
    if user_type == "PATIENT":
        if patient_id is not None and patient_id != user_ref_id:
            raise HTTPException(status_code=403, detail="Patients can only view their own records")
        patient_id = user_ref_id  # 患者只能查自己

    return get_prescriptions_with_payment_status(db, patient_id=patient_id)



@router.get("/unpaid/{patient_id}", response_model=List[PrescriptionResponse])
def read_unpaid_prescriptions_by_patient(patient_id: int, db: Session = Depends(get_db),user=Depends(require_user(UserType.ADMIN,  UserType.PATIENT))):
    return get_unpaid_prescriptions_by_patient(db, patient_id)

@router.post("/pharmacist/{prescription_id}/{pharmacist_id}", response_model=PrescriptionResponse)
def deal_prescription(prescription_id:int,pharmacist_id:int, db: Session = Depends(get_db),user=Depends(require_user(UserType.ADMIN,  UserType.PHARMACIST))):

    return pharmacist_deal_prescription(db, prescription_id,pharmacist_id)
